import React from 'react';
import style from './style.module.less';

interface IInputIntercept {
  intercept: (onChange: any) => (value: any) => void;
  children: JSX.Element;
  onChange?: (value: any) => void;
  value?: any;
}

/**
 * 输入拦截器
 */
export class InputIntercept extends React.Component<IInputIntercept> {
  render() {
    const { intercept, value, onChange, children } = this.props;
    return (
      <>
        {React.cloneElement(children, {
          value,
          onChange: intercept(onChange),
        })}
      </>
    );
  }
}

interface IMultilineInput {
  children: JSX.Element;
  delButton?: JSX.Element; // 删除按钮
  addButton?: JSX.Element; // 添加按钮
  onChange?: (value: any[]) => void;
  value?: any[];
}

/**
 * 多行输入字段
 */
export class MultilineInput extends React.Component<IMultilineInput> {
  add = () => {
    const { value = [], onChange } = this.props;
    value.push(undefined);
    onChange!(value);
  };

  del = (index: number) => {
    const { value = [], onChange } = this.props;
    value.splice(index, 1);
    onChange!(value);
  };

  onChange = (index: number) => (e: any) => {
    const { value = [], onChange } = this.props;
    value[index] = e && e.target ? e.target.value : e;
    onChange!(value);
  };

  render() {
    const { delButton, addButton, children, value = [] } = this.props;
    return (
      <>
        {value.map((val: any, index: number) => (
          <div className={style.multilineInputItem} key={index}>
            <div className={style.main}>
              {React.cloneElement(children, {
                value: val,
                onChange: this.onChange(index),
              })}
            </div>
            <div className={style.del} onClick={() => this.del(index)}>
              {delButton || '删除'}
            </div>
          </div>
        ))}
        <span className={style.multilineInputAdd} onClick={this.add}>
          {addButton || '添加'}
        </span>
      </>
    );
  }
}
